package com.gadglet.admin.gadget.client;

import com.gadglet.admin.gadget.shared.FieldVerifier;
import com.gadglet.admin.gadget.shared.GadgetTransit;
import com.gadglet.params.GadgetType;
import com.gadglet.params.SharedConstants;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class GadgetAdmin implements EntryPoint {

	private final GadgetServiceAsync asyService = GWT
			.create(GadgetService.class);

	@Override
	public void onModuleLoad() {
		final GadgetTransit gadget = new GadgetTransit();

		// build Form
		final Label errorLabel = new Label();
		final Button sendButton = new Button("Save");
		final TextBox nameField = new TextBox();
		final TextBox titleField = new TextBox();
		final TextBox helpUrlField = new TextBox();
		final TextBox gadgetFileNameField = new TextBox();
		final TextArea xmlSourceField = new TextArea();
		final ListBox statusField = new ListBox();
		final ListBox typeField = new ListBox();
		final TextBox handlerClassNameField = new TextBox();
		final ListBox gadgletTypeField = new ListBox();

		final TextArea descriptionField = new TextArea();
		
		titleField.setWidth("300px");
		helpUrlField.setWidth("300px");
		gadgetFileNameField.setWidth("300px");
		handlerClassNameField.setWidth("300px");

		descriptionField.setWidth("600px");
		descriptionField.setHeight("300px");

		xmlSourceField.setHeight("600px");
		xmlSourceField.setWidth("600px");

		statusField.addItem("Test", (new Integer(
				SharedConstants.gadgetStatusTest)).toString());
		statusField.addItem("On Line", (new Integer(
				SharedConstants.gadgetStatusOnLine)).toString());
		statusField.addItem("Off Line", (new Integer(
				SharedConstants.gadgetStatusOffLine)).toString());
		statusField.setVisibleItemCount(1);

		gadgletTypeField.addItem("Minglet", GadgetType.MINGLET.getGadgetType());
		gadgletTypeField.addItem("Bizlet", GadgetType.BIZLET.getGadgetType());
		gadgletTypeField.addItem("Other", GadgetType.OTHER.getGadgetType());

		typeField.addItem("iGoogle", (new Integer(
				SharedConstants.gadgetGoogleTypeiGoogle)).toString());
		typeField.addItem("Spreadsheet", (new Integer(
				SharedConstants.gadgetGoogleTypeSpreadsheets)).toString());
		typeField.addItem("GMail Context", (new Integer(
				SharedConstants.gadgetGoogleTypegMailContext)).toString());
		typeField.addItem("Calander Evnent", (new Integer(
				SharedConstants.gadgetGoogleTypeCalendarEvent)).toString());
		typeField.setVisibleItemCount(1);

		if (Location.getParameter("gname") != null) {
			// load object from server when gnage= ??? and save in gadget
			asyService.getGadget(Location.getParameter("gname"),
					new AsyncCallback<GadgetTransit>() {
						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}

						@Override
						public void onSuccess(GadgetTransit result) {
							if (result != null) {
								// set values
								descriptionField.setValue(result
										.getDescription());
								nameField.setValue(result.getName());
								nameField.setReadOnly(true);
								titleField.setValue(result.getTitle());

								xmlSourceField.setValue(result.getXmlSource());
								helpUrlField.setValue(result.getHelpUrl());
								typeField.setSelectedIndex(result.getType());
								statusField.setSelectedIndex(result.getStatus());
								
									
																
								for (int index = 0; index < gadgletTypeField
										.getItemCount(); index++) {
									if (result.getGadgletType()
											.equals(gadgletTypeField
													.getValue(index))) {
										gadgletTypeField.setSelectedIndex(index);
										
										break;
									}

								}

								gadgetFileNameField.setValue(result
										.getGadgetFileName());
								handlerClassNameField.setValue(result
										.getHandlerClassName());

							}
						}
					});

		}

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("titleFieldContainer").add(titleField);
		RootPanel.get("statusFieldContainer").add(statusField);
		RootPanel.get("googleTypeFieldContainer").add(typeField);
		RootPanel.get("typeFieldContainer").add(gadgletTypeField);
		RootPanel.get("handlerClassNameContainer").add(handlerClassNameField);

		RootPanel.get("helpUrlFieldContainer").add(helpUrlField);
		RootPanel.get("gadgetFileNameFieldContainer").add(gadgetFileNameField);

		RootPanel.get("descriptionFieldContainer").add(descriptionField);
		RootPanel.get("xmlSourceFieldContainer").add(xmlSourceField);

		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Add new Gadget");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		closeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the User clicks on the sendButton.
			 */
			@Override
			public void onClick(ClickEvent event) {
				sendNameToServer();
			}

			/**
			 * Fired when the User types in the nameField.
			 */
			@Override
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendNameToServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				// create gadget

				gadget.setName(nameField.getText());
				gadget.setTitle(titleField.getText());
				gadget.setHelpUrl(helpUrlField.getText());
				gadget.setGadgetFileName(gadgetFileNameField.getText());
				gadget.setDescription(descriptionField.getText());
				if (statusField != null)
					gadget.setStatus(Integer.parseInt(statusField
							.getValue(statusField.getSelectedIndex())));
				if (typeField != null)
					gadget.setType(Integer.parseInt(typeField
							.getValue(typeField.getSelectedIndex())));
				gadget.setXmlSource(xmlSourceField.getText());
				gadget.setHandlerClassName(handlerClassNameField.getValue());

				gadget.setGadgletType(gadgletTypeField
						.getValue(gadgletTypeField.getSelectedIndex()));
			

				errorLabel.setText("");
				String textToServer = gadget.getName();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel
							.setText("the name must have at least four characters");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");

				asyService.saveGadget(gadget, new AsyncCallback<String>() {
					@Override
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the User
						dialogBox.setText("Gadget - Failure");
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(caught.getMessage());
						dialogBox.center();
						closeButton.setFocus(true);
					}

					@Override
					public void onSuccess(String result) {

						dialogBox.setText("Saving Gadget");
						serverResponseLabel
								.removeStyleName("serverResponseLabelError");
						serverResponseLabel.setHTML(result);
						nameField.setReadOnly(true);
						dialogBox.center();
						closeButton.setFocus(true);
					}
				});

			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		// nameField.addKeyUpHandler(handler);
	}

}
